package com.stockz.train.dao;

import java.util.Collections;
import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.stockz.core.dao.hsql.BarDaoImpl;
import com.stockz.core.model.Bar;
import com.stockz.train.domain.intf.TrainingMarker;
import com.stockz.train.domain.model.TrainingSession;

@Repository
@Transactional
public class TrainingBarDaoImpl extends BarDaoImpl implements TrainingMarker {

	private TrainingSession trainingSession;
	private EntityManager entityManager;
	
	@PersistenceContext
    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }
	@Override
	public void setTrainingSession(TrainingSession trainingSession) {
		if(trainingSession == null){
			throw new IllegalArgumentException();
		}
		this.trainingSession = trainingSession;
	}
	
	@Override
	@SuppressWarnings("unchecked")
	@Transactional(propagation=Propagation.MANDATORY, readOnly=true)
	public List<Bar> getBarList(String code) {
		if(StringUtils.hasText(code)){
			Query query = entityManager.createNamedQuery("select b from Bar b where b.code = :code and b.date < :startDate order by b.date desc");
			query.setParameter("code", code);
			return query.getResultList();
		}
		return Collections.emptyList();
	}
	
	@Override
	@Transactional(propagation=Propagation.MANDATORY, readOnly=true)
	public Date getMaxBarDate() {
		return (Date)entityManager.createQuery("select max(b.date) from Bar b where b.date < :startDate")
				.setParameter("startDate", trainingSession.getStartDate()).getSingleResult();
	}
	
	@Override
	@SuppressWarnings("unchecked")
	@Transactional(propagation=Propagation.MANDATORY, readOnly=true)
	public List<Bar> getBarList(String code, int maxCount) {
		if(StringUtils.hasText(code)){
			Query query = entityManager.createNamedQuery("select b from Bar b where b.code = :code and b.date < :startDate order by b.date desc");
			query.setParameter("code", code);
			query.setParameter("startDate", trainingSession.getStartDate());
			query.setMaxResults(maxCount);
			return query.getResultList();
		}
		return Collections.emptyList();
	}
	
	
	
}
